#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import json
import os
import os.path
import re
import urllib.parse
import urllib.request
import sys
import configparser

def load_config():
    config = configparser.SafeConfigParser({
        "baseUrl": "http://localhost:8123/",
        "mode": "username",
        "variable": "USER",
        "secretToken": "",
    })
    config.read([
        "/etc/git-as-svn/git-lfs-authenticate.cfg",
        os.path.expanduser("~/.git-lfs-authenticate.cfg"),
        os.path.join(os.path.dirname(sys.argv[0]), "git-lfs-authenticate.cfg"),
    ])
    return config

parser = argparse.ArgumentParser()
parser.add_argument("repository", help="SSH repository path")
parser.add_argument("operation", help="Git LFS operation (upload or download)")
parser.add_argument("oid", help="OID (can be send by Git LFS v0.5.x clients)", nargs="?")
args = parser.parse_args()

config = load_config()
baseUrl = config.get("DEFAULT", "baseUrl")

mode = config.get("DEFAULT", "mode")

userId = os.getenv(config.get("DEFAULT", "variable"))
if userId is None:
    mode = "anonymous"
    userId = ""

secretToken = config.get("DEFAULT", "secretToken")

params = {
	"mode": mode,
	"userId": userId,
	"secretToken": secretToken,
}
params_encoded = urllib.parse.urlencode(params).encode()

url = "%s/%s/lfs_authenticate" % (baseUrl, args.repository)
response = urllib.request.urlopen(url, data=params_encoded)
sys.stdout.buffer.write(response.read())
